﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PSI.Models;
using PSI.Helper;
using System.Text;
using System.Dynamic;
using System.Collections.Specialized;

namespace PSI.Services {
    public class BaseCodeRuntimeService:PSIBaseService {


        public List<BaseCodeColumnMatedata> GetColnumsInfo(string basecodeid) { 

            var listColnmus=new List<BaseCodeColumnMatedata>();

            var strColnmus = new StringBuilder("select column_id,basecode_id,column_title,column_name,column_type,column_length,defualt_value,show_order,is_visible,display_fmt from psi_basecode_column_metadata where basecode_id=@bcid order by show_order");

            var p = CreateDbParameters();

            p.AddWithValue("bcid", basecodeid);

            Query(strColnmus.ToString(), p, ready => {

                listColnmus.Add(new BaseCodeColumnMatedata() { 
                 ColumnId=ready.GetString(0),
                 BasecodeId=ready.GetString(1),
                 ColumnTitle = ready.GetString(2),
                 ColumnName = ready.GetString(3),
                 ColumnType = ready.GetString(4),
                 ColumnLength = ready.GetInt32(5),
                 DefualtValue = ready.GetString(6),
                 ShowOrder = ready.GetInt32(7),
                 IsVisible = ready.GetInt32(8),
                 DisplayFmt = ready.GetString(9)
       
                });
            });

            return listColnmus;
        }

        public BaseCodeMetadata GetTableInfo(string basecodeid) {

            BaseCodeMetadata md = new BaseCodeMetadata();

            var strTable = new StringBuilder("select basecode_id,category_id,basecode_name,table_name,basecode_memo from psi_basecode_metadata where basecode_id=@bcid");

            var p = CreateDbParameters();

            p.AddWithValue("bcid", basecodeid);

            Query(strTable.ToString(), p, ready => {
                md.BasecodeId = ready.GetString(0);
                md.CategoryId = ready.GetString(1);
                md.BasecodeName = ready.GetString(2);
                md.TableName = ready.GetString(3);
                md.BasecodeMemo = ready.GetString(4);
            });

            return md;           
        }

        public List<dynamic> GetBaseCodeInfo(string basecodeid) {

            var list = new List<dynamic>();

            BaseCodeMetadata md = GetTableInfo(basecodeid);

            var listColnmus = GetColnumsInfo(basecodeid);

            var strcol="";
            foreach (var item in listColnmus) {
                strcol += item.ColumnName + ",";
            }

           strcol=strcol.Substring(0, strcol.Length - 1);

           var strInfo = new StringBuilder("select " + strcol + " from " + md.TableName + " ");

           Query(strInfo.ToString(), ready => {

               dynamic dc = new ExpandoObject();

               var temp = dc as IDictionary<string, object>;

               for (int i = 0; i < listColnmus.Count; i++) {

                    var yname=listColnmus[i].ColumnName;

                    switch(listColnmus[i].ColumnType)
                    {
                        case "varchar":
                            temp.Add(yname, ready.GetString(i));
                            break;
                        case "datetime":
                            temp.Add(yname,ready.GetDateTime(i));
                            break;
                        case "int":
                            temp.Add(yname, ready.GetInt32(i));
                            break;
                        case "float":
                            temp.Add(yname, ready.GetFloat(i));
                            break;
                    }
               }

               temp = temp.ToDictionary(x => x.Key, x => x.Value);

               list.Add(temp);

           });

            return list;
        
        }

        public Result AddbcInfo(NameValueCollection form)
        {
            var id = form["basecodeid"];

            var bccmd = GetColnumsInfo(id);

            var tablename = GetTableInfo(id);

            var rel = 0;

            if (form["bc_id"] == null) {

                var strup = "";
                var col = "";
                foreach (var item in bccmd) {
                    var cc = "@" + item.ColumnName;
                    col += item.ColumnName + ",";
                    strup += cc + ",";

                }

                col = col.Substring(0, col.Length - 1);
                strup = strup.Substring(0, strup.Length - 1);

                var InsertStr = new StringBuilder("insert " + tablename.TableName + " (" + col + ") values (" + strup + ") ");

                var p = CreateDbParameters();
                p.AddWithValue("bc_id", Guid.NewGuid().ToString());
                p.AddWithValue("create_user_id", UserService.GetLoginUser().Id);
                p.AddWithValue("create_dt", DateTime.Now);
                p.AddWithValue("last_update_user_id", "");
                p.AddWithValue("last_update_dt", null);
                foreach (var item in bccmd) {
                    if (item.IsVisible == 1) {
                        p.AddWithValue(item.ColumnName, form[item.ColumnName]);
                    }
                }

                rel = Execute(InsertStr.ToString(), p);
            } else {

                var col = "";
                foreach (var item in bccmd) {
                    if (item.IsVisible == 1) {
                        col += item.ColumnName + "=@" + item.ColumnName + ",";
                    }
                }

                var UpdataStr = new StringBuilder("update " + tablename.TableName + " set " + col + "last_update_user_id=@last_update_user_id,last_update_dt=@last_update_dt where bc_id=@bc_id");
                
                var p = CreateDbParameters();

                p.AddWithValue("bc_id", form["bc_id"]);
                p.AddWithValue("last_update_user_id", UserService.GetLoginUser().Id);
                p.AddWithValue("last_update_dt", DateTime.Now);

                foreach (var item in bccmd) {
                    if (item.IsVisible == 1) {
                        p.AddWithValue(item.ColumnName, form[item.ColumnName]);
                    }
                }
                rel = Execute(UpdataStr.ToString(), p);

            }

            if (rel > 0) {
                return new Result { Success=true};
            } else {
                return new Result { Success = false, Messgae = "系统出错,添加信息失败！" };
            }
        }

        public Result DeleteBaseCodeInfo(string basecodeid, string infoid) {

            BaseCodeMetadata md = GetTableInfo(basecodeid);

            var str = new StringBuilder("delete " + md.TableName + " where bc_id=@id");

            var p = CreateDbParameters();

            p.AddWithValue("id",infoid);

            var rel = Execute(str.ToString(), p);

            if (rel > 0)
                return new Result { Success = true };
            else
                return new Result { Success = false, Messgae = "系统错误,操作失败！" };
        }

    }
}













